#!/usr/bin/env python

import pypvm
import os
import sys
#from signal import SIGTERM
from sys import stdout
from time import sleep

try:
    print "MASTER: setting catchout to stdout..."
    pypvm.catchout(stdout)

    print "MASTER: spawning 2 tasks(prueba_esclavo02.py)..."
    slave_file = os.getcwd() + "/prueba_esclavo02.py"
    tids = pypvm.spawn(slave_file, [], pypvm.spawnOpts['TaskDefault'], "", 2)
    print "MASTER: spawned task's tid = %s" % tids

    print "MASTER: asking for notification on child exits..."
    pypvm.notify(pypvm.notifyDict['TaskExit'], 2, tids, 1)

    print "MASTER: initializing message buffer to PvmDataDefault..."
    pypvm.initsend(pypvm.data['default'])

    data = ["Soy de Cerro", "Soy del Ciclon", "Vengo de Bo. Obrero"]
    print("MASTER: packing %s..." % data)
    pypvm.pk(data)

    for recipient in tids:
        print("MASTER: sending data to tid %s..." % recipient)
        pypvm.send(recipient, 1)

    #print "MASTER: sleeping for 2 seconds (so slaves can catch up)..."
    #sleep(2)
    
    #print "MASTER: sending SIGTERM to children..."
    #for tid in tids:
    #    pypvm.sendsig(tid, SIGTERM)

    print "MASTER: calling nrecv ()..."
    pypvm.nrecv (tids[0], 1)

    results = [None, None]
    i = 0
    for sender in tids:
        print("MASTER: receiving data to tid %s..." % sender)
        pypvm.recv(sender, 2)
        results[i] = pypvm.upk()
        i += 1

    print "MASTER: printing results from slaves..."
    print results

    print "MASTER: killing slaves..."
    for tid in tids:
        pypvm.kill(tid)
        
    for tid in tids:
        pypvm.recv(-1, 2)
        print "MASTER: received an exit notification..."

    print "MASTER: exiting pvm..."
    pypvm.exit()

except:
    print "A pypvm error occured!"
    a =  sys.exc_info()
    print str(a[0])
    print a[1]
